package ar.edu.itba.twiteros.servlet;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import twitter4j.Paging;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import ar.edu.itba.twiteros.domain.UserIds;
import ar.edu.itba.twiteros.util.Facebook;
import ar.edu.itba.twiteros.util.GrantTwitterAccess;

@SuppressWarnings("serial")
public class TwiterosServlet extends HttpServlet {
	
	@Override
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {

	}
	
	@Override
	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		RequestDispatcher dispacher= getServletContext().getRequestDispatcher("/twitt.jsp");

		Long uid= Long.valueOf(req.getParameter("fb_sig_profile_user"));

		Twitter twitter = new Twitter();
		GrantTwitterAccess grantAccess= new GrantTwitterAccess(twitter, uid);
		
		req.setAttribute("f_key", Facebook.getFb_appkey());
		
		if(grantAccess.setAccessToken())
		{
			req.setAttribute("access", true);
			try {
				req.setAttribute("user", twitter.getAuthenticatedUser());
				//twitter.getUserTimeline()
				
				req.setAttribute("statuses", twitter.getUserTimeline(new Paging(1,10)));
			} catch (TwitterException e) {
				req.setAttribute("error_message", e.getMessage());
				dispacher= getServletContext().getRequestDispatcher("/error.jsp");
				dispacher.forward(req, resp);
			}
			
			
		}else{
			UserIds user= new UserIds(new Long(123), "Poli", "Bergez");
			req.setAttribute("access", false);
			req.setAttribute("url", user);//grantAccess.getUrl());
		}
			
		
		dispacher.forward(req, resp);
	}

}
